﻿using System;
using System.Collections;
using System.Configuration;
using System.Data;
using System.Linq;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.HtmlControls;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Xml.Linq;
using DCTAccess.Business;
using DCTLib.Common;
using DCTAccess.Business.Administrator;

public partial class AdminZone_AdminLogin : System.Web.UI.Page
{
    private string Message
    {
        set
        {
            lblError.Text = value;
        }
    }

    protected void Page_Load(object sender, EventArgs e)
    {
        Message = String.Empty;
        if (!IsPostBack)
        {

        }
    }

    protected void btnLogin_Click(object sender, EventArgs e)
    {
        Session.Remove(AppSessionKeys.ADMIN_INFO);
        CookieHelper.RemoveCookie(AppCookieKeys.ADMINID);
        CheckPermission(txtUsername.Text, txtPassword.Text);
    }

    private void CheckPermission(string username, string plainPassword)
    {
        Administrator loginAdmin = AdministratorController.GetAdministratorByUsername(username);
        if (loginAdmin != null)
        {
            if (loginAdmin.HashedPassword == MD5Helper.GetMD5Hash(plainPassword))
            {
                AppSessionInfo.CurrentAdministrator = loginAdmin;

                if (cbRemember.Checked)
                {
                    AppCookieInfo.AdminID = loginAdmin.ID;
                    AppCookieInfo.HashedPassword = loginAdmin.HashedPassword;
                    HistoryLogger.LogLoginAction(loginAdmin);
                }

                UpdateLastLoginDate(loginAdmin);
                RedirectPage();
            }
        }
        Message = AppMessages.LOGIN_FAIL;
    }

    public void UpdateLastLoginDate(Administrator loginAdmin)
    {
        Administrator admin = new Administrator();
        admin.ID = loginAdmin.ID;
        AdministratorController.UpdateLastLoginDate(admin);
    }

    private void RedirectPage()
    {
        if (!string.IsNullOrEmpty(AppRequestInfo.ReturnURL))
        {
            Response.Redirect(HttpUtility.UrlDecode(AppRequestInfo.ReturnURL));
        }
        else
        {
            Response.Redirect(AppUrls.AdminZone.HOMEPAGE);
        }
    }
}
